import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_problem.dart';
import 'package:flutter_learn_vi/src/bean/bean_problem_end.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/mine/new/score/mine_my_score_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_details_page.dart';
import 'package:flutter_learn_vi/src/page/topic/topic_enum.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class TopicEndPage extends StatefulWidget {
  final ProblemEndModel problemEndModel;
  final String pageTitle;
  final TopicEnum topicEnum;
  final String categoryOne;
  final String categoryTwo;

  TopicEndPage({
    @required this.problemEndModel,
    this.pageTitle,
    this.topicEnum,
    this.categoryOne,
    this.categoryTwo,
  });

  @override
  _TopicEndPageState createState() => _TopicEndPageState();
}

class _TopicEndPageState extends State<TopicEndPage> {
  List<ProblemModel> errorList = [];

  String _pageTitle;

  @override
  void initState() {
    super.initState();
    _pageTitle = widget.pageTitle;
    initData();
  }

  void initData() async {
    List<ProblemModel> list = widget.problemEndModel.questionAnswers;
    if (list != null) {
      list.forEach((element) {
        if (element.rightAnswer == "N") {
          errorList.add(element);
        }
      });

      submitError();
    }
  }

  @override
  Widget build(BuildContext context) {
    int score = widget.problemEndModel.obtainScore ~/ 10;

    String bgImage = "assets/images/3.0x/bg_fail_lower.webp";
    String centerImage = "assets/images/3.0x/bg_fraction3.png";
    if (score < 60) {
    } else if (score >= 60 && score < 90) {
      centerImage = "assets/images/3.0x/bg_fraction.png";
      bgImage = "assets/images/3.0x/bg_secondary_lower.png";
    } else {
      centerImage = "assets/images/3.0x/bg_fraction1.png";
      bgImage = "assets/images/3.0x/bg_excellentl_lower.png";
    }
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            Positioned.fill(
              child: Container(
                decoration: BoxDecoration(
                  gradient: LinearGradient(colors: [
                    Colors.lightBlueAccent.withOpacity(0.9),
                    Colors.blue.withOpacity(0.9)
                  ]),
                ),
              ),
            ),
            Positioned.fill(
              child: BackdropFilter(
                filter: ImageFilter.blur(sigmaX: 0.4, sigmaY: 0.4),
                child: Container(
                  color: Colors.white.withOpacity(0.4),
                ),
              ),
            ),
            Center(
              child: Container(
                width: 280,
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(4))),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      "答题结果",
                      style: TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 16,
                          color: Colors.blueGrey),
                    ),
                    SizedBox(
                      height: 2,
                    ),
                    Divider(),
                    SizedBox(
                      height: 14,
                    ),
                    buildPositioned(),
                    SizedBox(
                      height: 14,
                    ),
                    buildPositioned2(),
                    SizedBox(
                      height: 14,
                    ),
                    Divider(),
                    buildRow(context),
                    SizedBox(
                      height: 14,
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
              bottom: 60,
              left: 0,
              right: 0,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  GestureDetector(
                    onTap: () {
                      NavigatorUtils.pop(context);
                    },
                    child: ClipOval(
                      child: Container(
                        height: 50,
                        width: 50,
                        child: Icon(Icons.close),
                        color: Colors.white,
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildRow(BuildContext context) {
    if (widget.topicEnum == TopicEnum.muyCollect) {
      return SizedBox();
    }
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        OutlinedButton(
          child: Text("查看错题"),
          onPressed: () {
            if (errorList.length == 0) {
              ToastUtils.showToast("暂无错题可查看");
              return;
            }
            NavigatorUtils.openPageByFade(
              context,
              TopicDetilsPage(
                categoryOne: null,
                categoryTwo: null,
                topicEnum: TopicEnum.error,
                pageTitle: "我的错题",
                problemList: errorList,
              ),
            );
          },
        ),
        SizedBox(
          width: 14,
        ),
        buildNextWidget(context),
      ],
    );
  }

  ///查看我的成绩
  Widget buildCommonMyScoreWidget(BuildContext context) {
    if (widget.topicEnum == TopicEnum.pcTest) {
      return Container();
    }
    if (UserHelper.getInstance.userBean.isCheck != 0) {
      return Container();
    }
    return OutlinedButton(
      child: Text("我的积分记录"),
      onPressed: () {
        NavigatorUtils.openPageByFade(
            context,
            MyScorePage(
              scoreRankType: ScoreRankType.score,
            ),
            isReplace: true);
      },
    );
  }

  Widget buildNextWidget(BuildContext context) {
    if (widget.topicEnum == TopicEnum.pcTest ||
        widget.topicEnum == TopicEnum.muyCollect) {
      return Container();
    }
    return OutlinedButton(
      child: Text("再来一次"),
      onPressed: () {
        LogUtils.e("点击了再来一次 $_pageTitle");
        NavigatorUtils.openPageByFade(
            context,
            TopicDetilsPage(
              pageTitle: _pageTitle,
              categoryOne: widget.problemEndModel.categoryOne,
              categoryTwo: widget.problemEndModel.categoryTwo,
            ),
            isReplace: true);
      },
    );
  }

  Positioned buildScorePositioned(String centerImage) {
    return Positioned(
      left: 0,
      right: 0,
      top: 140,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Image.asset(
            centerImage,
            width: 200,
          ),
          buildColumn()
        ],
      ),
    );
  }

  Widget buildPositioned() {
    int answerTime = widget.problemEndModel.answerTime;
    int min = answerTime ~/ 60;
    int second = (answerTime % 60);
    String minStr = min > 9 ? "$min" : "0$min";
    String secondStr = second > 9 ? "$second" : "0$second";
    return Row(
      children: [
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.access_time,
          color: Colors.blueGrey,
        ),
        SizedBox(
          width: 8,
        ),
        Text(
          "用时 $minStr : $secondStr",
          style: TextStyle(color: Colors.blueGrey),
        ),
      ],
    );
  }

  Widget buildPositioned2() {
    num score = widget.problemEndModel.obtainScore /
        10 /
        widget.problemEndModel.extryScore;
    return Row(
      children: [
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.account_balance_wallet_outlined,
          color: Colors.blueGrey,
        ),
        SizedBox(
          width: 8,
        ),
        Text(
          "得分 $score",
          style: TextStyle(
            color: Colors.blueGrey,
          ),
        )
      ],
    );
  }

  Column buildColumn() {
    int score = widget.problemEndModel.obtainScore ~/ 10;
    String text = "";

    Color textColor = Colors.deepOrangeAccent;

    if (score < 60) {
      text = "不及格";
      textColor = Colors.deepOrangeAccent;
    } else if (score >= 60 && score < 90) {
      text = "继续努力";
    } else {
      text = "你真棒";
      textColor = Colors.green;
    }

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text(
          "$score",
          style: TextStyle(
              fontWeight: FontWeight.bold, fontSize: 53, color: textColor),
        ),
        Text(
          text,
          style: TextStyle(
              fontWeight: FontWeight.w500, fontSize: 23, color: textColor),
        ),
      ],
    );
  }

  ///提交错题
  Future<bool> submitError() async {
    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
        url: HttpHelper.submitErrorList +
            "?categoryOne=${widget.categoryOne}&categoryTwo=${widget.categoryTwo}",
        jsonMap: {
          "categoryOne": widget.categoryOne,
          "categoryTwo": widget.categoryTwo,
          "questionEntityList": errorList,
        });

    return Future.value(true);
  }
}
